package com.runfast.common.web.controller;

import com.runfast.common.exception.BaseException;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
@Slf4j
public class ExceptionController {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {


        Throwable cause = getCause(e);
        if (e instanceof BaseException) {
            BaseException baseException = (BaseException) e;
            return Result.fail(baseException.getErrorCode(),baseException.getMessage());
        } else if (e instanceof IllegalArgumentException||e instanceof BindException) {
            return Result.fail(ResultCode.PARAMETER_ERROR, e.getMessage());
        } else if (e instanceof UnauthorizedException) {
            return Result.fail(ResultCode.NO_AUTHORIZED);
        } else {
            log.error("", e);
            return Result.fail(ResultCode.SYSTEM_BUSY,e.toString());
        }

    }

    private Throwable getCause(Throwable e) {
        Throwable cause = e.getCause();
        if (cause != null) return getCause(cause);
        else return e;
    }
}
